package com.hyb.algorithm.data.struct.other;

/**
 * @BelongProject algorithm
 * @BelongPackage com.hyb.algorithm.data.struct.other
 * @Description 秒杀  随机丢弃部分请求
 * @ClassName SecondKillSimulator
 * @Author huyangbing
 * @Date 2025/1/2 23:35
 * @Version 1.0.0
 */
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class SecondKillSimulator {
    private final int totalItems; // 总共有多少件商品
    private final AtomicInteger soldItems; // 已售商品数量
    private final Random random = new Random(); // 随机数生成器
    private final double discardProbability; // 丢弃请求的概率

    public SecondKillSimulator(int totalItems, double discardProbability) {
        this.totalItems = totalItems;
        this.soldItems = new AtomicInteger(0);
        this.discardProbability = discardProbability;
    }

    // 尝试秒杀
    public boolean tryToKill(int userId) {
        // 检查是否还有商品可以售卖
        if (soldItems.get() >= totalItems) {
            return false;
        }

        // 根据概率随机丢弃请求
        if (random.nextDouble() < discardProbability) {
            return false;
        }

        // 如果通过了上面的检查，则标记为成功售卖
        soldItems.incrementAndGet();
        return true;
    }

    public static void main(String[] args) {
        SecondKillSimulator simulator = new SecondKillSimulator(100, 0.1); // 假设100件商品，10%的丢弃概率
        for (int i = 0; i < 1000; i++) { // 模拟1000个用户参与秒杀
            if (simulator.tryToKill(i)) {
                System.out.println("用户" + i + "成功秒杀");
            }
        }
    }
}